package com.xg.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xg.common.constant.CommonStatusEnum;
import com.xg.common.constant.TokenConstant;
import com.xg.common.response.TokenResponse;
import com.xg.common.result.ApiResult;
import com.xg.entity.User;
import com.xg.service.UserService;
import com.xg.util.CheckImgUtil;
import com.xg.util.Md5Util;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jdh
 * @since 2023-03-30
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

//    @RequestMapping("login")
//    public String usernamecheck(User user) {
//        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
//        if (!Func.isEmpty(user.getUserName())) {
//            queryWrapper.eq(User::getUserName,user.getUserName());
//        }
//        User one = userService.getOne(queryWrapper,false);
//        if (Func.isEmpty(one)) {
//        return "1";
//        }
//
//    }

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "Login";
    }

    @RequestMapping("/toReg")
    public String toReg(){
        return "Register";
    }

    @RequestMapping("/toPhoneLogin")
    public String toPhoneLogin(){
        return "PhoneLogin";
    }

@RequestMapping("/queryUserByName")
@ResponseBody
public String queryUserByName(String username) {
    User user = userService.queryUserByName(username);
    if (user !=null){
        return "1";
    }
    return "2";
}
    @RequestMapping("/queryUserPhone")
    @ResponseBody
    public String queryUserPhone(@RequestParam("userPhone") String userPhone){
        return userService.queryUserPhone(userPhone);
    }

    @RequestMapping("/queryUserEmail")
    @ResponseBody
    public String queryUserEmail(@RequestParam("userEmail") String userEmail){
        return userService.queryUserEmail(userEmail);
    }

    @RequestMapping("/register")
    @ResponseBody
    public void register(User user){
        userService.register(user);
    }

    @RequestMapping("imgcode")
    @ResponseBody
    public String imgcode(HttpServletRequest request, HttpServletResponse response) {
        String checkImg= null;
        try {
            checkImg= CheckImgUtil.checkImg(request, response);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return checkImg;
    }

    @RequestMapping("/login")
    @ResponseBody
    public String login(User user, HttpServletRequest request,HttpServletResponse response){
        ApiResult<TokenResponse> result;
        String checkCode = user.getCheckCode();
        if (StringUtils.isBlank(checkCode)){
            result = userService.checkVerificationCode(user.getUserPhone(),null,user.getVerificationCode());
            if (result.getCode() == CommonStatusEnum.VERIFICATION_CODE_ERROR.getCode()){
                return "0";
            }

            if (result.getCode() == CommonStatusEnum.VERIFICATION_CODE_NOT_EXISTS.getCode()){
                return "2";
            }

        }else {
            //从session中获得保存的验证码
            String checkcode = (String) request.getSession().getAttribute("checkcode");
            if (!checkCode.equals(checkcode)) {
                return "1";
            }
            //验证用户名是否存在
            User userRet = userService.queryUserByName(user.getUserName());
            if (userRet == null) {
                return "2";
            }
            //验证密码
            //获得用户的颜
            String salt = userRet.getSalt();
            String md516 = Md5Util.getMd516(user.getUserPassword() + salt);
            String md532 = Md5Util.getMd532(md516);
            if (!md532.equals(userRet.getUserPassword())) {
                return "3";
            }
            result = userService.checkVerificationCode(null,user.getUserName(),user.getVerificationCode());
            //把登陆的用户保存到session中
//            request.getSession().setAttribute("user", userRet);
        }
        
        TokenResponse data = result.getData();

        // 添加cookie信息
        Cookie successToken = new Cookie(TokenConstant.SUCCESS_TOKEN,data.getAccessToken());
        successToken.setMaxAge(7200);
        successToken.setDomain("localhost");
        successToken.setPath("/");
        Cookie refreshToken = new Cookie(TokenConstant.REFRESH_TOKEN, data.getRefreshToken());
        refreshToken.setMaxAge(10800);
        refreshToken.setDomain("localhost");
        refreshToken.setPath("/");
        response.addCookie(successToken);
        response.addCookie(refreshToken);

        return "success";
    }
}
